<?php
defined('APPLICATION_PATH')	or define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../'));
defined('APPLICATION_ENV')	or define('APPLICATION_ENV', 'development');

if (defined('BOOTSTRAP')) 
{
	require_once 'Zend/Loader/Autoloader.php';
	$loader = Zend_Loader_Autoloader::getInstance();
	$loader->setFallbackAutoloader(true);
}

$frontoptions = array(
                    'lifetime' => 20, 
                    'default_options' => array('cache_with_get_variables' => true),
                    'regexps' => array('^/backend/$' => array ('cache' => false)));

$backoptions = array('cache_dir' => APPLICATION_PATH . '/application/cache/');

$cache = Zend_Cache::factory('Page','File',$frontoptions,$backoptions);

$cache->start();  

Zend_Session::start();
Zend_Session::setOptions(array(
	'use_only_cookies'		=> TRUE,
	'strict'				=> TRUE,
	'remember_me_seconds'	=> 864000,
	'save_path'				=> APPLICATION_PATH . '/application/data/session',
	'name'					=> 'mhdevboard_', 
));

@date_default_timezone_set(@date_default_timezone_get());

class Main
{
	private $env;
	private $front;
	private $registry;
	private $config;
	
	public function __construct()
	{	
		$this->env 		= APPLICATION_ENV;
		$this->front 	= Zend_Controller_Front::getInstance();
		$this->registry = Zend_Registry::getInstance();
		
		if(APPLICATION_ENV == 'development')
		{
			error_reporting(E_ALL | E_STRICT);  
			ini_set('display_startup_errors', 1);  
			ini_set('display_errors', 1);
			$this->front->throwExceptions(true); 
		}
		elseif(APPLICATION_ENV == 'production')
		{
			ini_set('display_errors', false);
		}
		
		$this->init();
	}
	
	public function init()
	{
		$this->initConfig()
			->initControllers()
			->initLog()
			->initDb()
			->registerSettings()
			->initRoutes()
			->initPlugins()
			->initView();
	}
	
	public function initConfig()
	{
		$this->config = new Zend_Config_Ini(APPLICATION_PATH . '/application/config/mhdev.ini', $this->env);
		$this->registry->set('config', $this->config);
		return $this;
	}
    
	public function initControllers()
	{
		$this->front->setControllerDirectory(array(
			'default'	=> $this->config->appPath . '/controllers',
			'backend'	=> $this->config->appPath . '/backend/controllers'
		));
		return $this;
	}
	
	public function initDb()
	{
		try 
		{
			$db = Zend_Db::factory($this->config->db);
			Zend_Db_Table::setDefaultAdapter($db);		
			$db->query('SET NAMES "utf8";');
			$db->query('SET CHARACTER SET "utf8";');
			
			$this->registry->set('db', $db);
		} 
		catch (Zend_Exception $e) 
		{
			echo '<div style="width:500px; margin:0 auto; background-color:#f5f5f5;border:1px solid red; padding:5px;"><p>';
			echo '<strong>Caught exception</strong>: ' . get_class($e) . '<br /><br />';
    		echo '<strong>Message</strong>: ' . $e->getMessage();
    		echo '</p></div>';
    		exit();
		}

		return $this;
	}
	
	public function initView()
	{
		if(Zend_Registry::isRegistered('settings'))
		{
			// vars
			$settings	= $this->registry->get('settings');
			$auth 		= Zend_Auth::getInstance();
			
			// dynamic layout
			if($auth->hasIdentity())
			{
				// db
				$user		= new User();
				$getUser	= $user->find($auth->getIdentity()->uid);
				$arrUser	= $getUser->toArray();
				
				$layout = Zend_Layout::startMvc(array(
		            'layoutPath' => $this->config->appPath . '/layouts/' . $arrUser[0]['layout']
		        ));
		        
		        $view	= $layout->getView();
		        $view->setBasePath($this->config->appPath . '/views/' . $arrUser[0]['layout']);
			}
			else
			{
				// default layout
				$layout = Zend_Layout::startMvc(array(
	            	'layoutPath' => $this->config->appPath . '/layouts/default'
	        	));
	        	
	        	$view	= $layout->getView();
	        	$view->setBasePath($this->config->appPath . '/views/default');
			}
	
			$view->addHelperPath('MHDEV/View/Helper/', 'MHDEV_View_Helper_');
			
			Zend_Dojo::enableView($view);
			
			$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
			$viewRenderer->setView($view);
			
			$view->doctype('XHTML1_TRANSITIONAL');
			$view->headTitle($settings['board_name']);
			$view->headMeta()->appendHttpEquiv('Content-Type', 'text/html; charset=utf-8');
			
			/* DOJO DISABLED
			$view->dojo()->setDjConfigOption('usePlainJson', true)
				->setDjConfigOption('isDebug', $this->config->view->dojo->isDebug)
				->setLocalPath('/static/js/dojo/dojo.js')
				->disable();*/
		}
			
		return $this;
	}
	
	public function initRoutes()
	{
    	$router = new Zend_Controller_Router_Rewrite();
		$router->addConfig(
			new Zend_Config_Ini($this->config->appPath . '/config/frontend_routes.ini', $this->env), 
			'router'
		);
		
		$router->addConfig(
			new Zend_Config_Ini($this->config->appPath . '/config/backend_routes.ini', $this->env), 
			'router'
		);
		
		$this->front->setRouter($router); 
		
		return $this;
	}
	
	public function getRegistry($value)
	{
		return $this->registry->get($value);
	}
	
	public function initPlugins()
	{
		$this->front->registerPlugin(new MHDEV_Plugin_Acl(Zend_Auth::getInstance(), new MHDEV_Acl()));
		
		if(Zend_Registry::isRegistered('settings'))
		{
			$settings = $this->getRegistry('settings');
			if($settings['is_installed'] == 1)
			{
				$this->front->registerPlugin(new MHDEV_Plugin_Translation(Zend_Auth::getInstance()));
				$this->front->registerPlugin(new MHDEV_Plugin_UserOnline());
			}
		}
		
		return $this;
	}
	
	public function registerSettings()
	{
		try
		{
			// db
			$settings 		= new Settings();
			
			// query
			$getSettings	= $settings->fetchAll();
			$resSettings	= $getSettings->toArray();
			
			// register settings in registry		
			$this->registry->set('settings', $resSettings[0]);
		}
		catch (Zend_Exception $e)
		{
			$this->front->setDefaultControllerName('install');
			$this->front->setDefaultAction('index');
		}
		
		return $this;
	}
	
	public function initLog()
	{
		$writer 	= new Zend_Log_Writer_Stream('../application/data/log_' . date('Y-m-d', time()));
		
		$format 	= '%timestamp%;%priorityName%;(%priority%);%message%' . PHP_EOL;
		$formatter 	= new Zend_Log_Formatter_Simple($format);
		$writer->setFormatter($formatter);
		
		$logger 	= new Zend_Log($writer);

		// register log
		$this->registry->set('log', $logger);
		
		return $this;
	}

	public function debug($val)
	{
		return Zend_Debug::dump($val);
	}
	
	public function run()
	{
		return $this->front->dispatch();
	}
}

/*
 * Helperfunction
 */
function MHDEV_Sprintf($str, $vars)
{
    return str_replace(array_keys($vars), array_values($vars), $str);
}